package logic

import (
	"context"
	"errors"
	"log"
	"github.com/eeppee_admin/clouddisk/service/internal/svc"
	"github.com/eeppee_admin/clouddisk/service/helper"
	"github.com/eeppee_admin/clouddisk/service/internal/types"
	"github.com/eeppee_admin/clouddisk/service/model"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// http POST :8888/user/register name=damn password=12345678 email=1690544550@qq.com verify_email_code=175521
func (l *UserRegisterLogic) UserRegister(req *types.UserRegisterRequest) (resp *types.UserRegisterResponse, err error) {
	// 判断 验证码 是否一致
	verifyCode, err := l.svcCtx.RDB.Get(l.ctx, req.Email).Result()
	if err != nil {
		err =  errors.New("验证码错误")
		return 
	}

	if verifyCode != req.EmailCode {
		err = errors.New("验证码错误")
		return
	}

	// 判断 用户名 是否已经存在
	cnt, err := l.svcCtx.Engine.Where("name = ?", req.Name).Count(new(model.User))

	if err != nil {
		return
	}

	if cnt > 0 {
		err = errors.New("用户名已存在")
		return
	}

	// 写入用户
	user := &model.User{
		Identity: helper.UUID(),
		Name: req.Name,
		Password: helper.MD5(req.Password),
		Email: req.Email,
	}

	n, err := l.svcCtx.Engine.Insert(user)
	if err != nil {
		return nil, err
	}

	log.Println("insert user row: ", n)
	return
}
